﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using Intorise.Net;
using System.Drawing;
using Intorise.Common;
using System.Net;
using System.Threading;
using Config;
using System.Diagnostics;

namespace Model
{
    public partial class Player
    {
        public bool NeedUrl { get; set; }
        public CookieContainer Cookie { get; set; }
        public string Singn { get; set; }
        public byte[] GoldID { get; set; }
        public byte[] Version { get; set; }
        public long ID { get; set; }
        /// <summary>
        /// 仓库号
        /// </summary>
        public Warehouse Master { get; set; }
        public Account PlayerAccount { get; set; }
        public ProfessionEnum Profession { get; set; }
        public string AccountName { get; set; }
        public string ServerID { get; set; }
        public string Name { get; set; }
        /// <summary>
        /// 当前等级
        /// </summary>
        public int Level { get; set; }
        public Map CurrentMap { get; set; }
        public int CurrentHP { get; set; }
        public int CurrentMP { get; set; }
        public int TotalHP { get; set; }
        public int TotalMP { get; set; }
        public int TotalGold { get; set; }
        public bool IsRide { get; set; }
        public short X { get; set; }
        public short Y { get; set; }
        /// <summary>
        /// 是否自动打怪
        /// </summary>
        public bool AutoFight { get; set; }
        public bool PauseAutoFight { get; private set; }
        public bool Entered { get; set; }
        public bool NeedStudy { get; set; }
        public bool NeedPickupGold { get; set; }
        /// <summary>
        /// 当前线
        /// </summary>
        public int CurrentLine { get; set; }
        /// <summary>
        /// 配置的目标线路
        /// </summary>
        public int SetLine { get; set; }
        public long Exp { get; set; }
        public double ExpRange { get; set; }
        /// <summary>
        /// 当前装备的翅膀
        /// </summary>
        Thing currentWing = null;
        public List<Thing> Items = new List<Thing>();
        public List<Medicinal> medicinals = new List<Medicinal>();
        public List<Item> things = new List<Item>();
        public List<string> needGetTiems = new List<string>();
        public List<string> dontPickupTiems = new List<string>();
        public List<string> sellExcepet = new List<string>();
        public List<string> pickupItemName = new List<string>();
        public bool Trade { get; set; }
        public bool TradeOver { get; set; }
        public bool NeedLevel { get; set; }
        /// <summary>
        /// 是否有物品需要交易
        /// </summary>
        public bool NeedTrade { get; set; }

        /// <summary>
        /// 完成任务需要的等级
        /// </summary>
        public int CompletedLevel = 999;

        public PlayerStatusEnum Status
        {
            get
            {
                lock (statusLocker) { return status; }
            }
            set
            {
                lock (statusLocker)
                {
                    status = value;
                    if (status == PlayerStatusEnum.任务完成)
                    {
                        SaveCompleteHelper.SaveFinished(AccountName, ServerID);
                    }
                }
            }
        }
        /// <summary>
        /// 当前坐标
        /// </summary>
        public Point Location { get; set; }
        public Point FightLocation { get; set; }
        public static List<BotFightLocation> BotFightLocations { get; set; }
        /// <summary>
        /// 挂机地图和走路路线
        /// </summary>
        public FightLocation FightMapLocation { get; set; }
        /// <summary>
        /// 挂石头地图和走路路线
        /// </summary>
        public FightLocation CollectStoneMapLocation { get; set; }
        public Point MoveToPoint { get; set; }
        public int KilledCount { get; private set; }
        public int DeadCount { get; private set; }
        public int LoginCount { get; private set; }
        public string ItemInfo { get; private set; }

        public BotConfig Config { get; private set; }

        object statusLocker = new object();
        PlayerStatusEnum status;
        protected BotEngine engine = null;
        NetTools net = new NetTools();
        int lastKilledCount = 0;
        int lastLevel = 0;
        /// <summary>
        /// 连续因卡机而重新开始挂机的次数
        /// </summary>
        int reAutoFightCount = 0;
        public bool LogServerInfo = false;
        public bool LogDebugInfo = false;
        /// <summary>
        /// 是否已进入游戏
        /// </summary>
        bool gameEntered = false;
        bool giftGot = false;
        /// <summary>
        /// 是否需要终止当前操作
        /// </summary>
        bool cancelOperation = false;
        /// <summary>
        /// 主挂机脚本是否在运行
        /// </summary>
        bool scriptRunning = false;


        /// <summary>
        /// 主挂机脚本卡机检测是否在运行
        /// </summary>
        bool checkAutoFightRunning = false;
        Timer checkAutoFightTimer = null;//卡机检测定时器

        DateTime startAutoFightTime = DateTime.Now;
        /// <summary>
        /// 是否已签到
        /// </summary>
        bool singed = false;
        List<Medicinal> lastBuyMedicinals = new List<Medicinal>();

        #region AutoResetEvent
        object treatLocker = new object();
        object takeMedicinalLocker = new object();
        object pickupLocker = new object();
        #endregion

        #region timeout define
        DateTime lastTakMPMedicinalTime = DateTime.MinValue;
        DateTime lastTakHPMedicinalTime = DateTime.MinValue;
        #endregion

        /// <summary>
        /// 已拥有的技能
        /// </summary>
        List<Skill> LearnedSkills = new List<Skill>();
        List<Skill> skillList = new List<Skill>();
        MissionData missions = new MissionData();

        public Player(Account account, BotConfig config)
        {
            PlayerAccount = account;
            var text = PlayerAccount.Username.Split(new char[] { '_' }, StringSplitOptions.RemoveEmptyEntries);
            if (text.Length == 2)
            {
                PlayerAccount.Platform = text[0].ToLower();
                PlayerAccount.Username = text[1];
            }
            else
            {
                PlayerAccount.Platform = "";
            }
            AccountName = PlayerAccount.Username;
            ServerID = PlayerAccount.ServerID;
            PauseAutoFight = false;
            Status = PlayerStatusEnum.等待;
            this.Profession = ProfessionEnum.法师;
            CurrentHP = 999;
            CurrentMP = 999;
            TotalHP = 100;
            TotalMP = 10;
            this.Config = config;
            switch (PlayerAccount.Platform)
            {
                case "qd":
                    engine = new QdBotEngine(this);
                    break;
                case "yy":
                    engine = new YyBotEngine(this);
                    break;
                case "gm":
                    engine = new GmBotEngine(this);
                    break;
                default:
                    engine = new BotEngine(this);
                    break;
            }

            RefreshConfig();
            InitSkills();
            InitProcessor();
            checkAutoFightTimer = new Timer(new TimerCallback(CheckAutoFight), null, Timeout.Infinite, Timeout.Infinite);
        }

        public BotEngine Engine { get { return engine; } }

        public void RefreshConfig()
        {
            needGetTiems.Clear();
            if (Config.NeedPickupItems != null)
            {
                needGetTiems.AddRange(Config.NeedPickupItems.Split(new char[] { ',', '，', ' ' }, StringSplitOptions.RemoveEmptyEntries));
            }
            this.dontPickupTiems.Clear();
            if (Config.DontPickupItems != null)
            {
                dontPickupTiems.AddRange(Config.DontPickupItems.Split(new char[] { ',', '，', ' ' }, StringSplitOptions.RemoveEmptyEntries));
            }
            sellExcepet.Clear();
            if (Config.SellExcepet != null)
            {
                sellExcepet.AddRange(Config.SellExcepet.Split(new char[] { ',', '，', ' ' }, StringSplitOptions.RemoveEmptyEntries));
            }
            LogServerInfo = ((MainConfig)ConfigManager.ApplicationConfig).LogServerInfo;
            LogDebugInfo = ((MainConfig)ConfigManager.ApplicationConfig).LogDebugInfo;
        }

        public void CreateCharacter()
        {
            //if (engine.RemoteLogin())
            {
                engine.CreateCharacter();
            }
        }

        public bool Login()
        {
            Entered = false;
            LoginCount++;


            this.Status = PlayerStatusEnum.登录中;
            bool result = false;
            try
            {
                result = engine.RemoteLogin();
                //result = engine.LocalLogin();
                if (result)
                {
                    this.Status = PlayerStatusEnum.已登录;
                    ConsoleBLL.WriteLineInfo(this.ToString() + " 登录成功");
                    InitGameData();
                    result = engine.EnterGameServer();
                    if (result)
                    {
                        gameEntered = true;
                        this.Status = PlayerStatusEnum.已进入游戏;
                        ConsoleBLL.WriteLineInfo(this.ToString() + " 进入游戏成功，编号：" + this.ID.ToString());
                    }
                    else
                    {
                        gameEntered = false;
                        this.Status = PlayerStatusEnum.等待;
                        ConsoleBLL.WriteLineError(this.ToString() + " 进入游戏失败");
                    }
                }
                else
                {
                    if (LoginCount > Config.MaxLoginCount)
                    {
                        this.Status = PlayerStatusEnum.停止;
                    }
                    ConsoleBLL.WriteLineInfo(this.ToString() + " 登录失败");
                }
                return result;
            }
            catch (Exception ex)
            {
                ConsoleBLL.WriteLineError("登录出错：\r\n" + ex.Message + "\r\n" + ex.StackTrace);
                this.Status = PlayerStatusEnum.等待;
                return false;
            }
        }

        /// <summary>
        /// 初始化打怪技能
        /// </summary>
        private void InitSkills()
        {

        }

        /// <summary>
        /// 进入地图
        /// </summary>
        public void EnterMap()
        {
            //ConsoleBLL.WriteLine("进入地图");
            var command = Commands.GetCommand("进入地图");
            engine.SendData(command.Data);
        }

        /// <summary>
        /// 传送
        /// </summary>
        /// <param name="map"></param>
        public bool Transmit(Map map)
        {
            //ConsoleBLL.WriteLineInfo("传送到：" + map.Name);

            DateTime begin = DateTime.Now;
            var data = DataPackager.GetTransmitData(map);
            engine.SendData(data);
            Thread.Sleep(200);
            EnterMap();

            while (true)
            {
                Thread.Sleep(100);

                if (this.CurrentMap != null && this.CurrentMap.Name == map.Name)
                {
                    return true;
                }
                DateTime end = DateTime.Now;
                var span = end - begin;
                if (span.TotalSeconds > Config.TimeoutMove)
                {
                    break;
                }
            }

            //ConsoleBLL.WriteLineWaring("传送超时");
            return false;
        }

        public void ReAutoFight()
        {
            GameHelper.RunThreadPool(() =>
            {
                Transmit(Maps.GetMap("勇者大陆"));
                Thread.Sleep(1000);
                Quit();
            });
        }

        /// <summary>
        /// 移动
        /// </summary>
        /// <param name="target">目的地址坐标</param>
        public bool GoTo(Point target)
        {
            return GoTo(target.X, target.Y);
        }

        /// <summary>
        /// 移动
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        public bool GoTo(int x, int y, bool ride = true)
        {
            if (ride && !IsRide)
            {
                Ride();
            }
            int count = 0;
        begin:
            MoveToPoint = new Point(x, y);
            var data = DataPackager.GetWalkData(X, Y, new Point(x, y), 6);
            //ConsoleBLL.WriteLine("移动到：" + x + "，" + y);

            engine.SendData(data);

            DateTime begin = DateTime.Now;

            while (gameEntered && !cancelOperation)
            {
                Thread.Sleep(100);
                if (this.Location == MoveToPoint)
                {
                    Location = MoveToPoint;
                    return true;
                }
                DateTime end = DateTime.Now;
                var span = end - begin;
                if (span.TotalSeconds > Config.TimeoutMove)
                {
                    if (count < 1)
                    {
                        if (LogDebugInfo)
                        {
                            ConsoleBLL.WriteLineWaring(this + " 移动到：" + x + "," + y + "失败，重试...");
                        }
                        count++;
                        goto begin;
                    }
                    break;
                }
            }

            //ConsoleBLL.WriteLineError("移动超时");
            return false;
        }

        /// <summary>
        /// 战斗中移动(不检测是否到达)
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <returns></returns>
        public bool GoToFight(int x, int y)
        {
            MoveToPoint = new Point(x, y);
            var data = DataPackager.GetWalkData(X, Y, new Point(x, y), 6);
            engine.SendData(data);
            return true;
        }

        public bool GoTo(List<Point> points)
        {
            bool success = true;
            points.ForEach(x =>
            {
                success = success && GoTo(x);
                if (!success) { return; }
            });
            return success;
        }

        public void InitGameData()
        {
            initEvent.Reset();
            this.Location = Point.Empty;
            LearnedSkills.Clear();
            reAutoFightCount = 0;
            taskRunning = false;
            currentRunMission = null;
            AutoFight = false;
            scriptRunning = false;
            stopAllScriptRunning = false;
            stopRunning = false;
        }

        /// <summary>
        /// 执行脚本前准备(获取角色信息等)
        /// </summary>
        /// <returns>是否已准备好</returns>
        public virtual bool InitUserData()
        {
            #region 换线
            if (this.SetLine < 1)
            {
                if (Config.RandomLine)
                {
                    SetLine = new Random(new Random((int)DateTime.Now.Ticks).Next()).Next(10) + 1;
                }
                else
                {
                    this.SetLine = Config.LineNumber;
                    if (SetLine < 1)
                    {
                        SetLine = 1;
                    }
                }
            }
            Change(this.SetLine);
            Thread.Sleep(1000);
            #endregion

            Zuidui();//组队
            Thread.Sleep(1000);
            Tuizu();//退组

            DateTime begin = DateTime.Now;
            while (Level <= 0)
            {
                if (LogDebugInfo)
                {
                    ConsoleBLL.WriteLine(this + " 等待获取当前等级");
                }
                var seconds = (DateTime.Now - begin).TotalSeconds;
                if (seconds > 60)
                {
                    ConsoleBLL.WriteLineError(this + " 获取当前等级超时，退出..."); return false;
                }
                if (seconds > 30)
                {
                    EnterMap();
                    Zuidui();//组队
                    Thread.Sleep(300);
                    Tuizu();//退组
                }
                Thread.Sleep(1000);
            }

            //TradeMethod(null); return true;

            if (this.Level >= CompletedLevel)
            {
                SetTaskComplete(); return true;
            }

            {
                CleanPackage();//整理背包戴称号
            }
            Thread.Sleep(2000);

            Ride();
            #region 签到及领取奖励
            if (!singed)
            {
                singed = true;
                StartTimer();
            }
            #endregion
            if (this.Level == 1)
            {
                NeedStudy = true;
            }

            StudySkills();

            Get开学礼包();
            Get50级礼包();
            Get100级礼包();
            Get150级礼包();
            Get175级礼包();
            Get200级礼包();
            Get微信礼包();
            Get贵宾礼包();
            OpenMailBox();
            initEvent.Set();
            return true;
        }

        /// <summary>
        /// 执行脚本
        /// </summary>
        public virtual void Play()
        {
            if (!InitUserData())
            {
                ConsoleBLL.WriteLineError(this + "初始化游戏失败！"); Quit(PlayerStatusEnum.等待);
            }
        }

        /// <summary>
        /// 开始执行挂机脚本(新线程)
        /// </summary>
        public void PlayAutoFight()
        {
            GameHelper.RunGameThread(() =>
            {
                Thread.Sleep(500);
                Status = PlayerStatusEnum.开始挂机;
                ConsoleBLL.WriteLineInfo(this.ToString() + " 开始执行挂机脚本");

                try
                {
                    if (scriptRunning) { return; }
                    scriptRunning = true;
                    this.AutoFight = true;
                    cancelOperation = false;
                    if (GoFightLocation())
                    {
                        StartAutoFight();
                    }
                    else
                    {
                        ConsoleBLL.WriteLineError(this + "前往挂机地点失败，退出...");
                        Quit(PlayerStatusEnum.等待);
                    }
                }
                catch (Exception ex)
                {
                    ConsoleBLL.WriteLineError(this + " 执行挂机脚本时出现错误：\r\n" + ex.Message + "\r\n" + ex.StackTrace);
                }
                finally
                {
                    scriptRunning = false;
                    ConsoleBLL.WriteLineInfo(this.ToString() + " 挂机脚本已结束");
                }
                if (!gameEntered)
                {
                    this.Status = PlayerStatusEnum.已断线;
                }
            });
        }

        /// <summary>
        /// 开始自动打怪
        /// </summary>
        public void StartAutoFight()
        {
            if (string.IsNullOrEmpty(Thread.CurrentThread.Name))
            {
                Thread.CurrentThread.Name = "StartAutoFight";
            }
            else
            {
                ConsoleBLL.WriteLineWaring(this + "线程名称错误：" + Thread.CurrentThread.Name);
            }

            this.Status = PlayerStatusEnum.自动打怪;
            AutoFight = true;
            ConsoleBLL.WriteLineInfo(this.ToString() + " 开始自动打怪.");
            if (IsRide)
            {
                Ride();
            }

            startAutoFightTime = DateTime.Now;

            Exp = 0;
            ExpRange = 0;

            StartCheckAutoFight();

            DateTime lastCheckLocationTime = DateTime.Now;
            DateTime lastRandomLocationTime = DateTime.Now;

            var oldLocation = FightLocation;
            if (taskRunning)
            {
                oldLocation = this.Location;
            }
            Change(this.SetLine);//切换到目标线
            while (AutoFight && gameEntered && !cancelOperation)
            {
                if (PauseAutoFight)
                {
                    Thread.Sleep(100); continue;
                }

                lock (LearnedSkills)
                {
                    foreach (var skill in LearnedSkills)
                    {
                        if (IsRide)
                        {
                            Ride();
                        }
                        if (skill.IsFixedCD)
                        {
                            if ((DateTime.Now - skill.LastUseTime).TotalSeconds < skill.CD) { continue; }
                        }
                        else
                        {
                            if ((DateTime.Now - skill.LastUseTime).TotalSeconds < skill.CD * Config.HLBCD) { continue; }
                        }
                        if (skill.MP > this.CurrentMP) { continue; }
                        var monsters = engine.GetNearestMonster(skill.TargetCount);
                        if (monsters.Count == 0)
                        {
                            if (LogDebugInfo) { ConsoleBLL.WriteLine(this + " 没有找到怪物."); }
                            Thread.Sleep(1000);
                        }
                        else
                        {
                            KillMonster(skill, monsters);
                        }
                        if (!AutoFight || !gameEntered || cancelOperation) { break; }
                        Thread.Sleep(100);
                    }
                }

                if (!AutoFight || !gameEntered || cancelOperation) { break; }

                if ((DateTime.Now - lastRandomLocationTime).TotalSeconds > 10)//每10秒移动一次
                {
                    if (AutoFight && gameEntered && !cancelOperation) { var point = GameHelper.GetRandomLocation(oldLocation); GoToFight(point.X, point.Y); }
                    lastRandomLocationTime = DateTime.Now;
                }

                if ((DateTime.Now - lastCheckLocationTime).TotalSeconds > 30 && GameHelper.GetDistance(Location, oldLocation) > 10)
                {
                    //ConsoleBLL.WriteLineInfo("回到指定的挂机坐标");
                    if (AutoFight && gameEntered && !cancelOperation) { GoTo(oldLocation); }
                    lastCheckLocationTime = DateTime.Now;
                }

                if (!AutoFight || !gameEntered || cancelOperation) { break; }
                Thread.Sleep(100);
            }

            ConsoleBLL.WriteLineInfo(this.ToString() + " 自动挂机线程已经结束");
        }

        protected bool GoFightLocation()
        {
            if (taskRunning) { return true; }//如果正在执行特殊任务
            FightMapLocation = null;
            if (missions.快速升级.IsCompleted)
            {
                ConsoleBLL.WriteLine(this + "已完成快速升级任务，开始挂石头...");
                FightMapLocation = CollectStoneMapLocation;
                if (FightMapLocation == null)
                {
                    ConsoleBLL.WriteLineWaring(this + "挂石头的挂机地点为空，使用练级地点");
                }
            }
            if (FightMapLocation == null)
            {
                FightMapLocation = Player.BotFightLocations.OrderByDescending(w => w.Level).FirstOrDefault(w => this.Level >= w.Level);//查找当前等级应该去的练级地址
            }

            if (FightMapLocation == null)
            {
                ConsoleBLL.WriteLineError(this + string.Format("{0}:{1}未找到练级地点！将在当前地点开始挂机", AccountName, ServerID));
                FightLocation = Location;
                return true;
            }
            else
            {
                ConsoleBLL.WriteLineWaring(this + "挂机地址：" + FightMapLocation.MapName + " " + FightMapLocation.LocationName);
                FightLocation = FightMapLocation.LocationPoints.LastOrDefault();
                this.Status = PlayerStatusEnum.前往挂机地点;
                DateTime begin = DateTime.Now;
                while (gameEntered && this.Location == Point.Empty && !cancelOperation)
                {
                    DateTime end = DateTime.Now;
                    var span = end - begin;
                    if (span.TotalSeconds > Config.TimeoutMove)
                    {
                        break;
                    }

                    Transmit(Maps.GetMap(FightMapLocation.MapName, this.PlayerAccount.Platform));
                    Thread.Sleep(1000);
                }

                if (Location == Point.Empty)
                {
                    ConsoleBLL.WriteLineError(this + "获取当前坐标失败！");
                    return false;
                }
            }


            if (CurrentMap != null && CurrentMap.Name == FightMapLocation.MapName)
            {
                if (GameHelper.GetDistance(Location, FightLocation) < 20)
                {
                    if (GoTo(FightLocation)) { return true; }
                }
            }

            var map = Maps.GetMap(FightMapLocation.MapName);
            if (map == null || !gameEntered)
            {
                return false;
            }
            if (!Transmit(map) || !gameEntered) { return false; };
            EnterMap();
            foreach (Point p in FightMapLocation.LocationPoints)
            {
                int count = 1;
                while (count < 4)
                {
                    if (!gameEntered && !cancelOperation) { return false; }
                    if (GoTo(p))
                    {
                        break;
                    }
                    Thread.Sleep(1000);
                    ConsoleBLL.WriteLineError(this + string.Format("移动到{0}失败，重试第{1}次！", p, count));
                    count++;
                }
                if (count == 4)
                {
                    return false;
                }
            }

            ConsoleBLL.WriteLine(this + "已到达挂机地点");
            return true;
        }

        /// <summary>
        /// 启动卡机检测定时器
        /// </summary>
        protected void StartCheckAutoFight()
        {
            ConsoleBLL.WriteLine(this + " 启动卡机检测定时器");
            checkAutoFightTimer.Change(Config.TimeoutKilledCount * 1000, Config.TimeoutKilledCount * 1000);
        }

        /// <summary>
        /// 停止卡机检测定时器
        /// </summary>
        protected void StopCheckAutoFight()
        {
            ConsoleBLL.WriteLine(this + " 停止卡机检测定时器");
            checkAutoFightTimer.Change(Timeout.Infinite, Timeout.Infinite);
        }

        protected void CheckAutoFight(object obj)
        {
            if (!Monitor.TryEnter(checkAutoFightTimer)) { return; }
            checkAutoFightRunning = true;
            //ConsoleBLL.WriteLineInfo(this.ToString() + " 开始卡机检测.");
            try
            {
                DateTime lastCheckTime = DateTime.Now;

                if (AutoFight && lastKilledCount == KilledCount)
                {
                    ConsoleBLL.WriteLineWaring(this.ToString() + " " + Config.TimeoutKilledCount + "秒内杀怪数没有变化，重新开始挂机程序！");
                    if (AutoFight)
                    {
                        reAutoFightCount++;
                        if (reAutoFightCount < 3)
                        {
                            GameHelper.RunGameThread(ReFight);
                        }
                        else
                        {
                            Quit(PlayerStatusEnum.等待);
                        }
                    }
                }
                else
                {
                    lastKilledCount = KilledCount;
                }
            }
            catch (Exception ex)
            {
                GameHelper.Handle(ex);
            }
            finally
            {
                checkAutoFightRunning = false;
                Monitor.Exit(checkAutoFightTimer);
                //ConsoleBLL.WriteLineInfo(this.ToString() + " 结束卡机检测.");
            }
        }

        /// <summary>
        /// 1级学习技能
        /// </summary>
        private void StudySkills()
        {
            LearnedSkills.Clear();
            if (this.Level < 48)
            {
                LearnedSkills.Add(Skills.GetSkill("陨石术"));
            }
            LearnedSkills.Add(Skills.GetSkill("龙卷风"));

            if (!NeedStudy)//学习技能
            {
                return;
            }

            engine.SendData(new byte[] { 0x00, 0x00, 0x00, 0x07, 0x00, 0x08, 0x03, 0xDD, 0xCA, 0x9C, 0x01 });  //学习多重箭
            Thread.Sleep(500);
            engine.SendData(new byte[] { 0x00, 0x00, 0x00, 0x07, 0x00, 0x08, 0x03, 0xDD, 0xCC, 0x9C, 0x01 });  //学习穿透箭
            Thread.Sleep(500);
            engine.SendData(new byte[] { 0x00, 0x00, 0x00, 0x07, 0x00, 0x08, 0x03, 0xDD, 0xCE, 0x9C, 0x01 });  //学习五重箭
            //   Thread.Sleep(1000);
            engine.SendData(new byte[] { 0x00, 0x00, 0x00, 0x07, 0x00, 0x08, 0x03, 0xDD, 0xB8, 0x9C, 0x01 });  //学习陨石术
            Thread.Sleep(500);
            engine.SendData(new byte[] { 0x00, 0x00, 0x00, 0x07, 0x00, 0x08, 0x03, 0xDD, 0xBA, 0x9C, 0x01 });  //学习龙卷风
            Thread.Sleep(500);

            engine.SendData(new byte[] { 00, 0x00, 0x00, 0x10, 0x00, 0x02, 0x00, 0x8C, 0xC2, 0x9A, 0x0C, 0xBC, 0x05, 0xA6, 0x02, 0x00, 0x00, 0xF6, 0xAB, 0x01 });  //移动到老板娘
            Thread.Sleep(200);
            engine.SendData(new byte[] { 00, 0x00, 0x00, 0x08, 0x00, 0x01, 0x8B, 0x57, 0xC0, 0x16, 0xA4, 0x0C });  //进入地图
            Thread.Sleep(200);
            engine.SendData(new byte[] { 00, 0x00, 0x00, 0x04, 0x00, 0x01, 0x8B, 0x5B });  //任务
            Thread.Sleep(1000);
            engine.SendData(new byte[] { 0x00, 0x00, 0x00, 0x0A, 0x00, 0x01, 0xD5, 0x8A, 0x00, 0x00, 0xF6, 0xAB, 0x01, 0x00 });  //老板娘
            Thread.Sleep(1000);
            engine.SendData(new byte[] { 00, 0x00, 0x00, 0x10, 0x00, 0x02, 0x00, 0x8C, 0xC2, 0x9A, 0x0C, 0xCA, 0x04, 0x8C, 0x02, 0x00, 0x00, 0xF8, 0xAB, 0x01 });  //移动到幻影导师
            Thread.Sleep(200);
            engine.SendData(new byte[] { 00, 0x00, 0x00, 0x08, 0x00, 0x01, 0x8B, 0x57, 0xC0, 0x16, 0xA4, 0x0C });  //进入地图
            Thread.Sleep(200);
            engine.SendData(new byte[] { 00, 0x00, 0x00, 0x04, 0x00, 0x01, 0x8B, 0x5B });  //任务
            Thread.Sleep(500);

            engine.SendData(new byte[] { 0x00, 0x00, 0x00, 0x0A, 0x00, 0x01, 0xD5, 0x8A, 0x00, 0x00, 0xF8, 0xAB, 0x01, 0x00 });  //幻影导师

            Thread.Sleep(1000);
            engine.SendData(new byte[] { 0x00, 0x00, 0x00, 0x08, 0x00, 0x01, 0x8b, 0x5a, 0xC2, 0x9A, 0x0C, 0x00 });  //勇者大陆
            Thread.Sleep(200);
            EnterMap();
        }

        /// <summary>
        /// 暂停自动打怪
        /// </summary>
        public void Pause()
        {
            this.PauseAutoFight = true;
            this.Status = PlayerStatusEnum.已登录;
        }

        public void Continue()
        {
            this.PauseAutoFight = false;
            this.Status = PlayerStatusEnum.自动打怪;
        }

        public bool OpenMail(long item)
        {
            engine.SendData(DataPackager.GetOpenMailData(this, item));
            return true;
        }

        /// <summary>
        /// 提取附件
        /// </summary>
        /// <param name="f">信件编号</param>
        private void GetMailItem(byte[] f)
        {
            engine.SendData(DataPackager.GetGetMailItemData(f));
            return;
        }

        /// <summary>
        /// 打开邮箱
        /// </summary>
        /// <returns></returns>
        public bool OpenMailBox()
        {
            if (LogDebugInfo)
            {
                ConsoleBLL.WriteLineInfo(this + "读取信件...");
            }
            engine.SendData(DataPackager.GetOpenMailBoxData());
            return true;
        }

        public bool UseItem(Thing item)
        {
            if (LogDebugInfo)
            {
                ConsoleBLL.WriteLine(this + "使用" + item.Name);
            }
            engine.SendData(DataPackager.GetUseItemData(this, item)); return true;
        }

        public bool EquipItem(Thing item)
        {
            engine.SendData(DataPackager.GetEquipItemData(item)); return true;
        }

        public bool ReceiveRegisterItem()
        {
            engine.SendData(new byte[] { 0x00, 0x00, 0x00, 0x08, 0x00, 0x09, 0x28, 0x28, 0x00, 0x00, 0x00, 0x01 });
            return true;
        }

        public bool ReceiveRegisterItem(byte count)
        {
            var data = Tools.Contact(new byte[] { 0x00, 0x00, 0x00, 0x05, 0x00, 0x02, 0x52, 0x8B }, count);
            engine.SendData(data);
            return true;
        }

        public bool TiLian(Thing thing)
        {
            ConsoleBLL.WriteLineInfo(this + " 神器提炼");
            engine.SendData(DataPackager.GetTiLianData(thing)); return true;
        }

        public bool UsePackage(Thing item)
        {
            engine.SendData(DataPackager.GetUsePackageData(this, item));
            return true;
        }

        public bool ZhuangBei(long InstanceID, byte[] version, Enum装备类型 i)
        {
            ConsoleBLL.WriteLineInfo(this + " 穿装备");
            engine.SendData(DataPackager.GetZhuangBeiData(InstanceID, version, i));
            return true;
        }

        public bool TakeMedicine(Medicinal medicinal)
        {
            lock (takeMedicinalLocker)
            {
                DateTime lastTime;
                if (medicinal.Name.Contains("治疗"))
                {
                    lastTime = lastTakHPMedicinalTime;
                }
                else
                {
                    lastTime = lastTakMPMedicinalTime;
                }
                DateTime now = DateTime.Now;
                if ((now - lastTime).TotalSeconds < medicinal.CD)
                {
                    if (LogDebugInfo)
                    {
                        ConsoleBLL.WriteInfo(this + "CD没到");
                    }
                    return false;
                }
                if (LogDebugInfo)
                {
                    ConsoleBLL.WriteLineInfo(this + "吃" + medicinal.Name);
                }
                engine.SendData(DataPackager.GetUseItemData(this, medicinal));

                //engine.SendData(DataPackager.GetSellData(this, medicinal));


                if (medicinal.Name.Contains("治疗"))
                {
                    lastTakHPMedicinalTime = DateTime.Now;
                }
                else
                {
                    lastTakMPMedicinalTime = DateTime.Now;
                }
                lock (medicinals)
                {
                    lock (medicinal)
                    {
                        medicinal.Count--;
                        if (medicinal.Count <= 0)
                        {
                            medicinals.Remove(medicinal);
                        }
                    }
                }
            }
            return true;
        }

        public bool BuyMedicine(Medicinal medicinal, int count = 1)
        {
            lock (lastBuyMedicinals)
            {
                var item = lastBuyMedicinals.FirstOrDefault(w => w.Name == medicinal.Name);
                if (item != null)
                {
                    if ((DateTime.Now - item.CreateDate).TotalSeconds > 10)
                    {
                        //ConsoleBLL.WriteLineWaring("上次购买的物品已超过10秒还未完成，移除待购买物品！");
                        lastBuyMedicinals.Remove(item);
                    }
                    else
                    {
                        //ConsoleBLL.WriteLineInfo("上次购买还未完成");
                    }
                    return true;
                }
                else
                {
                    lastBuyMedicinals.Add(medicinal);
                }
            }
            if (LogDebugInfo)
            {
                ConsoleBLL.WriteLineInfo(this + "购买" + medicinal.Name + "x" + count);
            }
            engine.SendData(DataPackager.GetBuyMedicinalData(medicinal, count));
            return true;
        }

        public bool GetItem(ItemDropedMsg item)
        {
            lock (pickupLocker)
            {
                PauseAutoFight = true;
                if (LogDebugInfo)
                {
                    ConsoleBLL.WriteLine(string.Format(this + " 拾取物品{0}({1}/{2})", item.DropedItem.Name, item.X / 25, item.Y / 25));
                }
                var sourcePoint = Location;
                var distance = GameHelper.GetDistance(Location, new Point(item.X / 25, item.Y / 25));
                if (distance > Config.GetItemDistance)
                {
                    GoTo(item.X / 25, item.Y / 25, true);
                }
                Thread.Sleep(50);
                engine.SendData(DataPackager.GetItemData(this, item.DropedItem));
                //Thread.Sleep(10);
                //engine.SendData(DataPackager.GetItemData(item.DropedItem));
                GoTo(sourcePoint);
                PauseAutoFight = false;
            }
            return true;
        }

        /// <summary>
        /// 治疗
        /// </summary>
        /// <param name="type"></param>
        public void Treat(Thing.MedicinalType type)
        {
            GameHelper.RunThreadPool(() =>
            {
                Medicinal medicinal = null;
                lock (medicinals)
                {
                    medicinal = medicinals.FirstOrDefault(w => w.Type == (int)type);
                }
                if (medicinal == null)
                {
                    medicinal = Thing.GetThing(type);
                    BuyMedicine(medicinal, 1);
                }
                else
                {
                    TakeMedicine(medicinal);
                }
            });
        }

        public bool KillMonster(Skill skill, List<Monster> monsters)
        {
            byte[] data = null;
            data = DataPackager.GetAttactData(this, monsters, skill);
            if (LogDebugInfo)
            {
                ConsoleBLL.WriteLine(this + string.Format(" 使用{0}攻击{1}个怪物.", skill.Name, monsters.Count));
            }
            monsters.ForEach(m =>
            {
                m.AttackedCount++;
            });
            engine.SendData(data);
            //engine.SendData(data);
            skill.LastUseTime = DateTime.Now;
            return true;
        }

        public bool KillMonster(Skill skill, Monster monster)
        {
            var data = DataPackager.GetAttactData(this, monster, skill);
            skill.LastUseTime = DateTime.Now;
            if (LogDebugInfo)
            {
                ConsoleBLL.WriteLine(this + string.Format(" 使用{0}攻击{1}个怪物.", skill.Name, monster.InstanceID));
            }
            engine.SendData(data);
            return true;
        }

        public bool Ride()
        {
            //if (Level < 100) { return true; }
            IsRide = !IsRide;
            engine.SendData(DataPackager.GetRideData());
            return true;
        }

        public bool Sell(Thing item)
        {
            if (LogDebugInfo)
            {
                ConsoleBLL.WriteLineInfo("出售" + item.Name);
            }
            engine.SendData(DataPackager.GetSellData(this, item));
            return true;
        }

        public bool Sell1(long InstanceID)
        {

            engine.SendData(DataPackager.GetSellData1(this, InstanceID));
            return true;
        }

        public void Signin()
        {
            GameHelper.RunThreadPool(new Action(() =>
            {
                while (true)
                {
                    var command = Commands.GetCommand("签到");
                    ConsoleBLL.WriteLine("签到");
                    engine.SendData(command.Data);
                    Thread.Sleep(24 * 60 * 60 * 1000);
                }
            }));
        }

        public void Change(int line)
        {
            if (LogDebugInfo)
            {
                ConsoleBLL.WriteLine(this + " 选线" + line);
            }
            this.CurrentLine = line;
            engine.SendData(DataPackager.GetChangeLine(line));
            Thread.Sleep(100);
            EnterMap();
        }

        /// <summary>
        /// 加血
        /// </summary>
        /// <param name="hp"></param>
        public void TreatHP(int hp, int HpMax)
        {
            this.CurrentHP = hp;
            if (HpMax == 1)
            {
                if (TotalHP < CurrentHP) { TotalHP = CurrentHP; }
            }
            if (CurrentHP == 0)
            {
                ConsoleBLL.WriteLineError(this.ToString() + " 死亡，重新开始挂机...");
                //Thread.Sleep(5000);

                //engine.SendData(new byte[] { 0x00, 0x00, 0x00, 0x04, 0x00, 0x01, 0x93, 0x21 }); //回安全区复活
                //CurrentHP = TotalHP;
                DeadCount++;
                GameHelper.RunGameThread(ReFight);
                return;
            }
            if (this.CurrentHP >= TotalHP)
            {
                return;
            }
            if (TotalHP - this.CurrentHP >= Config.HP2)
            {
                Treat(Thing.MedicinalType.HP2);
            }
            else if (TotalHP - this.CurrentHP >= Config.HP1)
            {
                Treat(Thing.MedicinalType.HP1);
            }
            else if (TotalHP - this.CurrentHP >= Config.HP0)
            {
                Treat(Thing.MedicinalType.HP0);
            }
        }
        public void TreatHP1(int hp)
        {
            this.CurrentHP = hp;

            //if (CurrentHP == 0)
            //{
            //    ConsoleBLL.WriteLineError(this.ToString() + " 死亡，重新开始挂机...");
            //    Thread.Sleep(5000);

            //    engine.SendData(new byte[] { 0x00, 0x00, 0x00, 0x04, 0x00, 0x01, 0x93, 0x21 }); //回安全区复活
            //    //CurrentHP = TotalHP;
            //    DeadCount++;
            //    GameHelper.RunThread(ReFight);
            //    return;
            //}
            if (this.CurrentHP >= TotalHP)
            {
                return;
            }
            if (TotalHP - this.CurrentHP >= Config.HP2)
            {
                Treat(Thing.MedicinalType.HP2);
            }
            else if (TotalHP - this.CurrentHP >= Config.HP1)
            {
                Treat(Thing.MedicinalType.HP1);
            }
            else if (TotalHP - this.CurrentHP >= Config.HP0)
            {
                Treat(Thing.MedicinalType.HP0);
            }
        }

        /// <summary>
        /// 复活
        /// </summary>
        public void Revive()
        {
            var datas = DataPackager.GetRevive();
            datas.ForEach(x =>
            {
                engine.SendData(x);
                Thread.Sleep(100);
            });
        }

        public void Quit(PlayerStatusEnum status = PlayerStatusEnum.等待)
        {
            GameHelper.RunGameThread(() =>
            {
                StopAllScript(status);
                engine.Stop();
            });
        }

        public override string ToString()
        {
            return AccountName + " " + ServerID + " " + Name + " ";
        }

        private void SumItems(List<IGrouping<string, Thing>> list)
        {
            StringBuilder sb = new StringBuilder();
            list.ForEach(e =>
            {
                sb.Append(e.FirstOrDefault().Name + "(" + e.Count() + ") ");
            });
            this.ItemInfo = sb.ToString();
        }

        private bool IsNeedSell(string name)
        {
            foreach (string s in sellExcepet)
            {
                if (name.Contains(s)) { return false; }
            }
            return true;
        }

        /// <summary>
        /// 重新开始挂机，此方法必须在新线程中运行
        /// </summary>
        protected void ReFight()
        {
            if (!Monitor.TryEnter(this, 3000)) { ConsoleBLL.WriteLineWaring(this + " Player Monitor.TryEnter false!"); return; }
            StopCheckAutoFight();
            try
            {
                if (CurrentHP <= 0)
                {
                    Thread.Sleep(10000);
                    Revive();
                }
                if (!StopRunScript(PlayerStatusEnum.重新开始挂机)) { Quit(PlayerStatusEnum.等待); return; }

                GameHelper.RunGameThread(() => { PlayAutoFight(); });
            }
            finally
            {
                Monitor.Exit(this); ConsoleBLL.WriteLineWaring(this + " Player Monitor.Exited");
            }
        }

        protected void GetMail()
        {
            engine.SendData(new byte[] { 0x00, 0x00, 0x00, 0x04, 0x00, 0x01, 0xE4, 0xF7 });
        }

        /// <summary>
        /// 到120级后收集物品
        /// </summary>
        public void Collect()
        {
            this.Status = PlayerStatusEnum.交易物品;
            Trade = false;
            TradeOver = true;
            NeedTrade = false;
            NeedLevel = true;



            //Transmit(Maps.GetMap("勇者大陆"));
            //Thread.Sleep(1000);
            //GoTo(405, 166);
            //engine.SendData(new byte[] { 0x00, 0x00, 0x00, 0x0A, 0x00, 0x01, 0xD5, 0x8A, 0x00, 0x00, 0xB6, 0x8D, 0x06, 0x00 }); //领祝福
            Items.Clear();
            int j = 0;
            int k = 0;
            // Bgein:
            if (!Get贵宾礼包())
            {//领取贵宾礼品
                Quit(PlayerStatusEnum.等待);
                Status = PlayerStatusEnum.等待;
                return;
                //k++;
                //goto Bgein;

            }
            //if (j < 10 && NeedLevel == false)
            //{
            //    j++;

            //        ConsoleBLL.WriteLineError(string.Format("领取失败，重试！", this));
            //        goto Bgein;


            //}
            j = 0;
            Thread.Sleep(5000);//等待贵宾物品邮件
        打开邮件:
            mailboxOpend.Reset();
            engine.SendData(new byte[] { 0x00, 0x00, 0x00, 0x04, 0x00, 0x01, 0xE4, 0xF7 }); //打开邮件
            if (!mailboxOpend.WaitOne(1000 * 10))
            {
                ConsoleBLL.WriteLineError(string.Format("打开邮件超时！", this));
                Quit(PlayerStatusEnum.等待);
                Status = PlayerStatusEnum.等待;
                Thread.Sleep(500);
                return;
            }
            Thread.Sleep(1000);
            cleanBackpackEvent.Reset();
            贵宾物品已获得.Reset();
            tradeCompleted = true;
            engine.SendData(new byte[] { 0x00, 0x00, 0x00, 0x04, 0x00, 0x01, 0x97, 0x0D }); //整理背包
            if (!cleanBackpackEvent.WaitOne(1000 * 10))
            {
                ConsoleBLL.WriteLineError(string.Format("等待整理背包超时！", this));
                Quit();
                Status = PlayerStatusEnum.等待;
                Thread.Sleep(500);
                return;
            }


            if (!贵宾物品已获得.WaitOne(5 * 1000))
            {
                ConsoleBLL.WriteLineError(string.Format("获取贵宾物品超时！", this));

                if (TradeOver == false && Trade == false)
                {
                    ConsoleBLL.WriteLineError(string.Format("今天己交易！", this));
                    Quit(PlayerStatusEnum.任务完成);
                    Status = PlayerStatusEnum.任务完成;
                    Thread.Sleep(500);
                    return;
                }
                else if (TradeOver == false && Trade == true)
                {
                    goto Trade;
                }
                //if (j < 5)
                //{
                //    j++;
                //    goto 打开邮件;
                //}
                //else
                //{
                Quit(PlayerStatusEnum.等待);
                Status = PlayerStatusEnum.等待;
                Thread.Sleep(500);
                return;
                // }
            }
            // 寻宝:

            寻宝结果.Reset();
            engine.SendData(new byte[] { 00, 0x00, 0x00, 0x05, 0x00, 0x08, 0x0F, 0x4A, 0x01 }); //寻宝
            if (!寻宝结果.WaitOne(10 * 1000))
            {
                ConsoleBLL.WriteLineError(string.Format("获取寻宝结果超时！", this));
                Quit(PlayerStatusEnum.等待);
                Status = PlayerStatusEnum.等待;
                Thread.Sleep(500);
                return;
            }

            engine.SendData(new byte[] { 00, 0x00, 0x00, 0x06, 0x00, 0x08, 0x0F, 0x4C, 0x00, 0x04 });  //放入背包1

            寻宝结果.Reset();
            engine.SendData(new byte[] { 00, 0x00, 0x00, 0x05, 0x00, 0x08, 0x0F, 0x4A, 0x01 }); //寻宝
            if (!寻宝结果.WaitOne(10 * 1000))
            {
                ConsoleBLL.WriteLineError(string.Format("获取寻宝结果超时！", this));
                Quit(PlayerStatusEnum.等待);
                Status = PlayerStatusEnum.等待;
                Thread.Sleep(500);
                return;
            }
            engine.SendData(new byte[] { 00, 0x00, 0x00, 0x06, 0x00, 0x08, 0x0F, 0x4C, 0x02, 0x04 });  //放入背包2

            if (Trade == false)
            {
                ConsoleBLL.WriteLineError(string.Format("没有交易物品！", this));
                Quit(PlayerStatusEnum.任务完成);
                Status = PlayerStatusEnum.任务完成;
                Thread.Sleep(500);
                return;
            }

            cleanBackpackEvent.Reset();
            Thread.Sleep(5000);
            engine.SendData(new byte[] { 0x00, 0x00, 0x00, 0x04, 0x00, 0x01, 0x97, 0x0D }); //整理背包
            if (!cleanBackpackEvent.WaitOne(1000 * 10))
            {
                ConsoleBLL.WriteLineError(string.Format("等待整理背包超时！", this));
                Quit();
                Status = PlayerStatusEnum.等待;
                Thread.Sleep(500);
                return;
            }



            if (Items.Count == 0 && Trade == true)
            {
                ConsoleBLL.WriteLineError(string.Format("没有取出交易物品！", this));
                Quit();
                Thread.Sleep(500);
                Status = PlayerStatusEnum.等待
                    ;
                return;
            }

            if (Items.Count > 0)
            {
                ConsoleBLL.WriteLine("有物品需要交易：");
                Items.ForEach(x =>
                {
                    ConsoleBLL.WriteLineInfo(x.Name);
                });
            }
            j = 0;
        Trade:

            Transmit(Master.CurrentMap);    //移动到仓库号所在地图
            Thread.Sleep(1000);
            Change(2); //换线

            tradeEvent.Reset();
            InviteTrade(Master.ID);
            //等待对方同意(60秒超时)
            if (!tradeEvent.WaitOne(1000 * 10))
            {
                if (j < 5)
                {
                    j++;
                    goto Trade;
                }
                else
                {
                    ConsoleBLL.WriteLineError(string.Format("等待{0}同意交易超时，交易取消！", this));
                    Status = PlayerStatusEnum.等待;
                    return;
                }
            }
            lock (Items)
            {
                for (int i = 0; i < Items.Count && i < 6; i++)
                {
                    PutItem(Items[i], (short)(i + 1));
                    Thread.Sleep(200);
                }

                Thread.Sleep(500);
                LockTrade();//发送锁定
            }
            // Thread.Sleep(500);
            tradeEvent.Reset();
            if (!tradeEvent.WaitOne(1000 * 10))
            {
                ConsoleBLL.WriteLineError(string.Format("等待{0}锁定交易超时，交易取消！", this)); //return;

                Quit();
                Status = PlayerStatusEnum.等待;
                return;
            }

            AffirmTrade();//发送确认

            Quit(PlayerStatusEnum.任务完成);
            Thread.Sleep(500);
        }

        object stopPlayLocker = new object();
        bool stopRunning = false;
        ManualResetEvent stopEvent = new ManualResetEvent(false);

        /// <summary>
        /// 终结者，用于停止打怪线程，返回是否成功停止
        /// </summary>
        public bool StopRunScript(PlayerStatusEnum playerStatus = PlayerStatusEnum.等待)
        {
            lock (stopPlayLocker)
            {
                if (stopRunning || stopAllScriptRunning) { return false; }
                stopRunning = true;
            }

            if (string.IsNullOrEmpty(Thread.CurrentThread.Name))
            {
                Thread.CurrentThread.Name = "终结者";
            }
            if (LogDebugInfo)
            {
                ConsoleBLL.WriteLineInfo(this + "终结者开始执行...");
            }
            AutoFight = false;
            cancelOperation = !taskRunning;
            StopCheckAutoFight();

            try
            {
                DateTime time = DateTime.Now;
                while (checkAutoFightRunning)
                {
                    if (LogDebugInfo)
                    {
                        ConsoleBLL.WriteLine(this + " 等待卡机检测线程结束");
                    }
                    Thread.Sleep(100);
                }
                ConsoleBLL.WriteLineInfo(this + " 卡机检测线程已停止运行");
                while (scriptRunning)
                {
                    if (LogDebugInfo)
                    {
                        ConsoleBLL.WriteLine(this + " 等待挂机脚本结束");
                    }
                    Thread.Sleep(100);
                }
                ConsoleBLL.WriteLineInfo(this + " 挂机脚本已停止运行");

                return true;
            }
            catch (ThreadAbortException) { ConsoleBLL.WriteLineInfo(this + "StopRunScript线程已被终止"); return false; }
            finally
            {
                lock (stopPlayLocker)
                {
                    stopRunning = false;
                }
                this.Status = playerStatus;
                cancelOperation = false;
                ConsoleBLL.WriteLineInfo(this + " 终结者执行结束");
            }
        }

        bool stopAllScriptRunning = false;

        /// <summary>
        /// 终结者，用于停止所有挂机线程，返回是否成功停止
        /// </summary>
        public bool StopAllScript(PlayerStatusEnum playerStatus = PlayerStatusEnum.等待)
        {
            lock (stopPlayLocker)
            {
                if (stopAllScriptRunning) { return false; }
                stopAllScriptRunning = true;
            }

            if (string.IsNullOrEmpty(Thread.CurrentThread.Name))
            {
                Thread.CurrentThread.Name = "StopAllScript";
            }
            if (LogDebugInfo)
            {
                ConsoleBLL.WriteLineInfo(this + "StopAllScript开始执行...");
            }
            AutoFight = false;
            cancelOperation = !taskRunning;
            StopCheckAutoFight();

            try
            {
                DateTime time = DateTime.Now;
                while (checkAutoFightRunning)
                {
                    if (LogDebugInfo)
                    {
                        ConsoleBLL.WriteLine(this + " 等待卡机检测线程结束");
                    }
                    Thread.Sleep(100);
                }
                ConsoleBLL.WriteLineInfo(this + " 卡机检测线程已停止运行");
                while (scriptRunning)
                {
                    if (LogDebugInfo)
                    {
                        ConsoleBLL.WriteLine(this + " 等待挂机脚本结束");
                    }
                    Thread.Sleep(100);
                }
                ConsoleBLL.WriteLineInfo(this + " 挂机脚本已停止运行");

                GameHelper.StopAllGameThread(this);
                return true;
            }
            finally
            {
                lock (stopPlayLocker)
                {
                    stopAllScriptRunning = false;
                }
                this.Status = playerStatus;
                cancelOperation = false;
                ConsoleBLL.WriteLineInfo(this + " StopAllScript执行结束");
            }
        }

        /// <summary>
        /// 断线
        /// </summary>
        public void Disconnect()
        {
            GameHelper.RunGameThread(() =>
            {
                gameEntered = false;
                if (!StopAllScript(PlayerStatusEnum.已断线)) { return; }
            });
        }

        /// <summary>
        /// 设置挂机任务为已完成
        /// </summary>
        public void SetTaskComplete()
        {
            this.status = PlayerStatusEnum.任务完成;
        }

        /// <summary>
        /// 挂机任务是否已完成
        /// </summary>
        /// <returns></returns>
        public bool IsTaskCompleted()
        {
            return this.status == PlayerStatusEnum.任务完成;
        }
    }
}
